import React from 'react';
import {connect} from 'dva';
import PropTypes from 'prop-types';
import {Row,Col,Form, Icon, Input, Button, Checkbox,Modal,Radio,Layout,message} from 'antd';
import style from '../styles/login.less';
import reqwest from 'reqwest';
import {Link} from 'dva/router'
import NumericInput from '../components/NumericInput.js'
import {numvail,selectvail} from '../utils/Validator.js'
import {creat_account} from '../models/Role.js'
import {reqwest_post,reqwest_get} from '../utils/Reqwest.js'
const {  Footer } = Layout;

const FormItem = Form.Item;
class Invit extends React.Component{
	constructor(props){
		super(props);
		this.state={
      visible:false,
      saler:[],
      salboss:null,
      t:this.props.location.query.t,
		}
	}
  handleRadioChange(e){
    const {saler} = this.state;
    const {value} = e.target;
    console.log(e)
    switch(value){
      case 'saler':this.handleModal(value)
      break;
      case 'acct':this.handleModal(value)
      break;
      case 'cs':this.handleModal(value)
      break;
      case 'operator':this.handleModal(value)
      break;
    }
    this.setState({userole:e.target.value});
  }
  handleOk(){
    // this.loadserver({
    //   mobile
    // })
    // debugger
    // const {getFieldsValue} =this.props.form;
    let values = this.props.form.getFieldsValue()
    // this.loadserver({
    //   mobile:values.mobile,
    //   password:values.password,
    //   name:userName,
    //   role:values.priseName,
    //   salerId:this.state.salboss,
    //   saler:[]
    // })

    this.setState({visible:false});
  }
  handleChange(e){
    // this.setState({visible:true});
    console.log(e+'-'+ e.key)
  }
  loadserver(data={}){
    console.log(data)
    let _this =this;
    // return
    let _role =data.role;
    let _user = null;
    if(_role=='saler'){
      _user ={mobile:data.mobile,name:data.name,role:data.role,password:data.password,director_id:_this.state.salboss}
    }else{
      _user ={mobile:data.mobile,name:data.name,role:data.role,password:data.password};
    }
    
    reqwest({
      url: window.host+'/api/sync/accounts/gen_account_user',
      method: 'post',
      crossOrigin: true,
      type: 'json',
      data:{actoken:this.props.location.query.t,
        user:_user,
      },
    }).then((data) => {
      // console.log(data);
        if(data.status=='success'){
          let set ={"mobile":data.current_user.mobile,"avatar":data.current_user.avatar,"avatar_url":data.current_user.avatar_url,"name":data.current_user.name,"role":data.current_user.role,"accout_name":data.current_user.account.name,"invit_url":data.current_user.account.invit_url}

           message.success('注册成功,将直接跳往首页',1,()=>{
            window.localStorage['token']=data.token;
            window.localStorage['curloe']=data.current_user.role;
            // debugger
            window.localStorage['menu']=JSON.stringify(data.menu);
            window.localStorage['cgj_id']=data.current_user.cgj_user_id;
            window.localStorage['account_type']=data.current_user.account_type;
            window.localStorage['userrr_id']=data.current_user.id;
            window.localStorage['setting']=JSON.stringify(set);
            // console.log(data.wallet)
            // window.localStorage['money'] = JSON.stringify(data.current_user.wallet)
            // window.localStorage['companies']=JSON.stringify(data.companies);
            // window.sessionStorage['material']=JSON.stringify(data.materials);
            // window.sessionStorage['store_tree']=JSON.stringify(data.stores_tree);
            // window.location.hash=window.location.hash
            window.location.hash='/app/home?curren=1';
         });
        }else{
          message.error(data.msg)
        } 
    }).fail((err,msg)=>{
      console.log(err)
    });
        
  }
  handleModal(value){
    let _this = this;
    reqwest_get('/api/accounts/get_directors',{t:_this.props.location.query.t,role:value},(data)=>{
      if(data.status=='success'){
        this.setState({
          saler:data.list,
          visible:true
        })
      }
    })
  }
  componentWillMount(){
    let _this = this;
  }
	handleSubmit(e){
	  
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      // values.mobile=this.state.phone
      // console.log(values)
      if (!err) {
        // if(values.priseName=='saler'){
        //   this.setState({visible:true})
        // }else{
          this.loadserver({
            mobile:values.mobile,
            name:values.userName,
            role:values.priseName
          })
        // }
      }
    });
	}
	render(){
      const nav =this.state.saler.map(function(data){
        return <Radio key={data.id} value={data.id}>{data.name}</Radio>
      })

		const { getFieldDecorator } = this.props.form;
    const _radioNode = creat_account.map((data)=>{
      return <Radio key={data.id} value={data.id}>{data.value}</Radio>
    })
		return(
			<Layout className={`${style.login_form}`} >
        <Col  xl={{span :6,offset:8}} lg={{span:8,offset:7}} md={{span:11,offset:6}} sm={{span :12,offset:5}} className={`${style.login_form_dec}`}>
          <h1>注册</h1>
          <Form onSubmit={this.handleSubmit.bind(this)}  >
         		 <FormItem >
              {getFieldDecorator('mobile', {
                rules: [{ required: true,validator:(rule,value,callback)=>{
                  numvail(rule,value,callback)
                }}],
              })(
                <Input  onChange={(e)=>{this.setState({username:e.target.value})}} prefix={<Icon type="mobile" style={{ fontSize: 14 }} />} placeholder="手机号" />                
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: '请输入密码', validator:(rule,value,callback)=>{
                  selectvail(rule,value,callback,rule.message)
                  }
                }]
              })(
                <Input prefix={<Icon type="lock" style={{ fontSize: 14 }} />} type="password" placeholder="密码 (6位以上，区分大小写)" />
              )}
            </FormItem>
            <FormItem >
              {getFieldDecorator('userName', {
                rules: [{ required: true, message: '请输入姓名' }],
              })(
                <Input prefix={<Icon type="user" style={{ fontSize: 14 }} />} placeholder="姓名" />
              )}
            </FormItem>
            <FormItem style={{marginBottom:8}}>
              {getFieldDecorator('priseName', {
                rules: [{ required: true, message: '请选择用户类型' }],
                initialValue:undefined
              })(
                <Radio.Group  onChange={this.handleRadioChange.bind(this)}>
                  {_radioNode}
                </Radio.Group>
              )}
            </FormItem>
            <FormItem className={`${style.login_form_right}`}>
              <Button style={{width:'100%'}} type="primary" htmlType="submit" className="login-form-button">
                注册
              </Button>
            </FormItem>
          </Form>
        </Col>
        <Footer className={`${style.login_footer}`}>
          <span>已有账号?</span><span><Link to={{pathname:'/'}}>去登录</Link></span>
        </Footer>
        <Modal title='选择销售主管' onOk={this.handleOk.bind(this)}
          onCancel={()=>{this.setState({visible:false})}} visible={this.state.visible}
        >
         <Radio.Group onChange={(e,b)=>{this.setState({salboss:e.target.value});}}>
            {nav}
          </Radio.Group> 
        </Modal>
      </Layout>
		)
	}
}

const InvitForm = Form.create()(Invit);
export default connect()(InvitForm);
